package com.glory.wxmemsicpda.activity

import android.os.Handler
import android.text.TextUtils
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.glory.wxmemsicpda.R
import com.glory.wxmemsicpda.adapter.MaterialsAdapter
import com.glory.wxmemsicpda.adapter.PageInfoAdapter
import com.glory.wxmemsicpda.base.App.Companion.app
import com.glory.wxmemsicpda.base.BaseDialogActivity
import com.glory.wxmemsicpda.bean.CheckSheetBean
import com.glory.wxmemsicpda.bean.SheetInfoBean
import com.glory.wxmemsicpda.bean.StartLotBean
import com.glory.wxmemsicpda.bean.net.BaseResponseBean
import com.glory.wxmemsicpda.databinding.ActivityAbortBinding
import com.glory.wxmemsicpda.utils.FileUtils
import com.glory.wxmemsicpda.utils.MyUtils
import com.glory.wxmemsicpda.utils.NetUtils
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.model.Response
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_SimpleDialogEntityCallBack
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils
import kotlinx.android.synthetic.main.activity_abort.*
import org.json.JSONObject

class AbortActivity : BaseDialogActivity(), View.OnClickListener {
    private var eqpId: String = ""
    private var lotId: String = ""
    private var testLotId: String = ""
    private var pageInfoList: MutableList<StartLotBean.PRODUCTLISTBean> = mutableListOf()
    private var pageInfoAdapter: PageInfoAdapter = PageInfoAdapter(pageInfoList)
    private var materialsList: MutableList<StartLotBean.MESMATLISTBean> = mutableListOf()
    private var materialsAdapter: MaterialsAdapter = MaterialsAdapter(materialsList)
    private var viewDataBinding: ActivityAbortBinding? = null

    private var tipDialog: FreeUI_GeneralFragmentDialog? = null
    private var testTypeList: MutableList<String> = mutableListOf()
    private var testTimeList: MutableList<String> = mutableListOf()
    private var mTestTypePop: FreeUI_GeneralPop? = null
    private var mTestTimePop: FreeUI_GeneralPop? = null
    private var sTestType = ""
    private var sTestTime = ""


    override fun getLayoutResId(): Int {
        return 0
    }

    override fun initView() {
        viewDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_abort)
        setTitle("批次退站操作")
        freeUI_titleView.setRightListener("批次退站") {
            requestStart()
        }
        eqpId = intent.getStringExtra("showPlugin")!!


        rvInfoList.layoutManager = LinearLayoutManager(this)
        rvInfoList.adapter = pageInfoAdapter

        requestData("")

//        llTestLotId.visibility = View.VISIBLE
//        etTestLotId.isFocusable = false
        etLotId.requestFocus()
//        etLotId.isFocusable = true
//        etLotId.isFocusableInTouchMode = true

    }

    private fun requestStart() {
//        val ss = "{\"Response\":{\"Header\":{\"TRANSACTIONID\":\"c5e5e318389d4c39b914e4c10ba519d4\",\"RESULT\":\"FAIL\",\"RESULTCODE\":null,\"RESULTMESSAGE\":\"请确认批次/设备是否输入！\"},\"Body\":null}}";
//        val dd : BaseResponseBean<*> = Gson().fromJson(ss,object : TypeToken<BaseResponseBean<*>>(){}.type)
//        if (dd!!.isSuccess(true, supportFragmentManager)) {
//            showToast("批次开始成功", true)
//            finish()
//        }
        val map = JsonObject()
        map.addProperty("EQP_ID", eqpId)
        map.addProperty("ACTIONTYPE", "DefaultAbort")
        val lotList = ArrayList<CheckSheetBean>()
        val lotBean = CheckSheetBean()
        lotBean.lotid = lotId
        lotList.add(lotBean)
        map.add(
                "LOTLIST",
        JsonParser().parse(Gson().toJson(lotList)).asJsonArray
        )
        NetUtils.requestPosNet(this,
            "LOTABORT", "MES.LOTABORT",
            map,
            object : FreeUI_SimpleDialogEntityCallBack<BaseResponseBean<*>?>(this) {
                override fun onSuccess(response: Response<BaseResponseBean<*>?>) {
                    super.onSuccess(response)
                    if (response.body()!!.isSuccess(false, supportFragmentManager)) {
//                        showToast("批次开始成功", true)
                        showMessageDialog(
                            "退站成功！",
                            supportFragmentManager
                        )
//                        finish()
                    }
                }

                override fun onError(response: Response<BaseResponseBean<*>?>) {
                    super.onError(response)
                    loadError(response.exception, "LOTABORT")
                }
            })
    }

    override fun initData() {
        MyUtils.setEditTextListener(etLotId, this) {
            lotId = it
            if (llTestLotId.visibility == View.GONE) {
                requestData(lotId)
            } else {
                combineLot(it)
            }
        }

        MyUtils.setEditTextListener(etTestLotId, this) {
            testLotId = it

            combineLot(it)

        }

        //获取本地Json数据
        val resultSetData = FileUtils.readJson(this, "test_eqp_info.txt")
        if (resultSetData.status === 0) {
            val sShortcutJson: String = resultSetData.getData().toString()
            if (!TextUtils.isEmpty(sShortcutJson)) {
                //解析JSON
                val jsonObject = JSONObject(sShortcutJson)
                val sTestType = jsonObject.getString("TESTTYPE")
                val sTestTime = jsonObject.getString("TestTime")
                val type = object :TypeToken<MutableList<String>>(){}.type
                testTypeList = Gson().fromJson<MutableList<String>>(sTestType, type)
                testTimeList = Gson().fromJson<MutableList<String>>(sTestTime, type)
            } else {
                showToast(resultSetData.msg, false)
            }
        }
    }

    private fun combineLot(sLotId : String) {
        if (lotId != "" && testLotId != "") {
            requestData("$lotId,$testLotId")
        } else if (lotId == "" && testLotId != "") {
            if (sLotId != ""){
                etLotId.requestFocus()
            }
        } else if (lotId != "" && testLotId == "") {

        }
    }

    private fun requestData(lotId: String) {
//        var ss = "{\"Response\":{\"Header\":{\"TRANSACTIONID\":\"c5e5e318389d4c39b914e4c10ba519d4\",\"RESULT\":\"SUCCESS\",\"RESULTCODE\":null,\"RESULTMESSAGE\":null},\"Body\":{\"LOT_ID\":\"\",\"EQP_ID\":\"MO-001\",\"EQP_RUN_STATE\":\"闲置中\",\"TRANSID\":\"0\",\"PRODUCT_LIST\":[{\"PNAME\":\"产品型号\",\"PVALUE\":\"\"},{\"PNAME\":\"数量\",\"PVALUE\":\"\"},{\"PNAME\":\"Recipe名称\",\"PVALUE\":\"\"}],\"MES_MAT_LIST\":[]}}}"
//        var dd : BaseResponseBean<StartLotBean> = Gson().fromJson(ss,object : TypeToken<BaseResponseBean<StartLotBean>>(){}.type)
//        if (dd!!.isSuccess(true, supportFragmentManager)) {
//            pageInfoList.clear()
//            materialsList.clear()
//            if (dd!!.response.body!!.producT_LIST.size > 0) {
//                pageInfoList.addAll(dd!!.response.body!!.producT_LIST)
//            }
//            if (dd!!.response.body!!.meS_MAT_LIST.size > 0) {
//                materialsList.addAll(dd!!.response.body!!.meS_MAT_LIST)
//            }
//            pageInfoAdapter.notifyDataSetChanged()
//            materialsAdapter.notifyDataSetChanged()
//            viewDataBinding?.entity = dd.response.body
//
//        }
        val map = JsonObject()
        map.addProperty("EQP_ID", eqpId)
        map.addProperty("LOT_ID", lotId)
        map.addProperty("TESTTYPE", sTestType)
        map.addProperty("TESTCOUNT", sTestTime)
        NetUtils.requestPosNet(this,
            "PDALotStartInfo", "PDALotStartInfo",
            map,
            object : FreeUI_SimpleDialogEntityCallBack<BaseResponseBean<StartLotBean?>?>(this) {
                override fun onSuccess(response: Response<BaseResponseBean<StartLotBean?>?>) {
                    super.onSuccess(response)
                    if (response.body()!!.response.getHeader().getRESULT().toUpperCase() == "SUCCESS") {
                        pageInfoList.clear()
                        materialsList.clear()
                        if (response.body()!!.response.body!!.producT_LIST.size > 0) {
                            pageInfoList.addAll(response.body()!!.response.body!!.producT_LIST)
                        }
                        if (response.body()!!.response.body!!.meS_MAT_LIST.size > 0) {
                            materialsList.addAll(response.body()!!.response.body!!.meS_MAT_LIST)
                        }
                        pageInfoAdapter.notifyDataSetChanged()
                        materialsAdapter.notifyDataSetChanged()
                        viewDataBinding?.entity = response.body()!!.response.body
                        //判断是否要显示第二个lot扫描框
                        if (response.body()!!.response.body!!.morE_LOT == "YES") {
                            llTestLotId.visibility = View.VISIBLE
                        }

                    }else{
                        tipDialog = FreeApi_DialogUtils.getConfirmDialog(
                            app, "确定", response.body()!!.response.getHeader().getRESULTMESSAGE()
                        ) {
                            finish()
                        }
                        tipDialog!!.show(supportFragmentManager, "DIALOG")
                    }
                }

                override fun onError(response: Response<BaseResponseBean<StartLotBean?>?>) {
                    super.onError(response)
                    loadError(response.exception, "PDALotStartInfo")
//                    Handler().postDelayed({ finish() }, 2000)
                }
            })
    }

    //消息提示框
    private fun showMessageDialog(message: String, fragmentManager: FragmentManager) {
        FreeApi_DialogUtils.getConfirmDialog(
            app, "确定", message
        ) {
            finish()
        }.show(fragmentManager, "DIALOG")

    }

    override fun getBaseEntity(): FreeUI_AddViewEntity {
        return FreeUI_AddViewEntity("header", llMain)
    }

    override fun onClick(p0: View?) {
        TODO("Not yet implemented")
    }
}
